{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "from nltk.corpus import wordnet\n",
    "\n",
    "# 获取同义词\n",
    "def get_synonyms(word):\n",
    "    synonyms = set()\n",
    "    for syn in wordnet.synsets(word):\n",
    "        for lemma in syn.lemmas():\n",
    "            synonyms.add(lemma.name().replace(\"_\", \" \"))\n",
    "    return list(synonyms)\n",
    "\n",
    "# 同义词替换\n",
    "def synonym_replacement(sentence, aspect_terms, n):\n",
    "    words = sentence.split()\n",
    "    new_words = words[:]\n",
    "    random.shuffle(aspect_terms)\n",
    "    for aspect in aspect_terms[:n]:\n",
    "        synonyms = get_synonyms(aspect)\n",
    "        if synonyms:\n",
    "            new_words = [synonyms[0] if word == aspect else word for word in new_words]\n",
    "    return ' '.join(new_words)\n",
    "\n",
    "# 随机插入\n",
    "def random_insertion(sentence, aspect_terms, n):\n",
    "    words = sentence.split()\n",
    "    for _ in range(n):\n",
    "        aspect = random.choice(aspect_terms)\n",
    "        synonyms = get_synonyms(aspect)\n",
    "        if synonyms:\n",
    "            insert_pos = random.randint(0, len(words))\n",
    "            words.insert(insert_pos, synonyms[0])\n",
    "    return ' '.join(words)\n",
    "\n",
    "# 随机交换\n",
    "def random_swap(sentence, n):\n",
    "    words = sentence.split()\n",
    "    for _ in range(n):\n",
    "        idx1, idx2 = random.sample(range(len(words)), 2)\n",
    "        words[idx1], words[idx2] = words[idx2], words[idx1]\n",
    "    return ' '.join(words)\n",
    "\n",
    "# 随机删除\n",
    "def random_deletion(sentence, p):\n",
    "    words = sentence.split()\n",
    "    if len(words) == 1:\n",
    "        return sentence\n",
    "    new_words = [word for word in words if random.uniform(0, 1) > p]\n",
    "    return ' '.join(new_words)\n",
    "\n",
    "# 数据增强主函数\n",
    "def augment_sentence(sentence, aspect_terms, alpha, operation):\n",
    "    n = max(1, int(alpha * len(sentence.split())))\n",
    "    if operation == \"SR\":\n",
    "        return synonym_replacement(sentence, aspect_terms, n)\n",
    "    elif operation == \"RI\":\n",
    "        return random_insertion(sentence, aspect_terms, n)\n",
    "    elif operation == \"RS\":\n",
    "        return random_swap(sentence, n)\n",
    "    elif operation == \"RD\":\n",
    "        return random_deletion(sentence, alpha)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
